package com.lanchetech.user.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lanchetech.bean.request.PageReq;
import com.lanchetech.bean.response.BasePageResp;
import com.lanchetech.bean.response.BaseResp;
import com.lanchetech.bean.response.ResultData;
import com.lanchetech.bean.util.PageHelpUtil;
import com.lanchetech.bean.vo.DiseaseReportVO;
import com.lanchetech.common.enums.ExpTypeEnum;
import com.lanchetech.common.enums.ToggleEnum;
import com.lanchetech.dao.DiseaseMapper;
import com.lanchetech.dao.DiseaseReportHistoryMapper;
import com.lanchetech.dao.DiseaseReportMapper;
import com.lanchetech.dao.UserRelationshipMapper;
import com.lanchetech.entity.*;
import com.lanchetech.service.ExpService;
import com.lanchetech.user.service.DiseaseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
public class DiseaseServiceImpl implements DiseaseService {


    @Autowired
    DiseaseMapper diseaseMapper;

    @Autowired
    DiseaseReportMapper diseaseReportMapper;

    @Autowired
    DiseaseReportHistoryMapper diseaseReportHistoryMapper;

    @Autowired
    ExpService expService;

    @Autowired
    UserRelationshipMapper userRelationshipMapper;

    @Override
    public ResultData<List<Disease>> getDiseaseList() {
        return new ResultData<>(diseaseMapper.findAll());
    }

    @Override
    public BaseResp editDiseaseReport(DiseaseReport req) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        DiseaseReport last = diseaseReportMapper.findOneByUserId(user.getId());

        // 发放学分
        expService.createExpFlow(user, Math.floorDiv(System.currentTimeMillis(), 604800000), ExpTypeEnum.CHECK_HEALTH);

        if(last == null){
            req.setUserId(user.getId());
            req.setCreatedAt(new Date());
            req.setUpdatedAt(new Date());
            diseaseReportMapper.insert(req);
        }else{
            last.setAge(req.getAge());
            last.setHeight(req.getHeight());
            last.setWeight(req.getWeight());
            last.setBloodSugar(req.getBloodSugar());
            last.setBloodPressure(req.getBloodPressure());
            last.setCurrent(req.getCurrent());
            last.setCurrentName(req.getCurrentName());
            last.setUpdatedAt(new Date());
            diseaseReportMapper.updateByPrimaryKeySelective(last);
        }

        DiseaseReportHistory dh = new DiseaseReportHistory();
        BeanUtils.copyProperties(req, dh);
        dh.setId(null);
        dh.setUserId(user.getId());
        dh.setCreatedAt(new Date());

        diseaseReportHistoryMapper.insert(dh);

        return new BaseResp();
    }

    @Override
    public ResultData<DiseaseReportVO> getDiseaseReportDetail(Long userId) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        DiseaseReport diseaseReport = null;
        Long finalUserId = user.getId();
        if(userId != null){
            // 判断是否是下级，并且是否允许查看
            UserRelationship userRelationship = userRelationshipMapper.findOneBySuperiorIdAndSubordinateId(user.getId(), userId);
            if(userRelationship != null){
                // 再看看是否允许查看
                DiseaseReport result = diseaseReportMapper.findOneByUserId(userId);
                if(result != null && result.getOtherView().equals(ToggleEnum.ON.getStatus())){
                    finalUserId = userId;
                    diseaseReport = result;
                }
            }
        }else{
            diseaseReport = diseaseReportMapper.findOneByUserId(finalUserId);
        }

        if(diseaseReport != null){
            DiseaseReportVO vo = new DiseaseReportVO();
            BeanUtils.copyProperties(diseaseReport, vo);
            vo.setDiseaseReportHistoryList(diseaseReportHistoryMapper.findLatestTwoByUserId(finalUserId));
            vo.setWeightHistoryList(diseaseReportHistoryMapper.findLatestFiveByUserId(finalUserId));
            return new ResultData<>(vo);
        }
        return new ResultData<>(null);
    }

    @Override
    public ResultData<BasePageResp<DiseaseReportHistory>> getDiseaseReportHistory(PageReq req) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(req.getUserId() != null){
            // 判断是否是下级，并且是否允许查看
            UserRelationship userRelationship = userRelationshipMapper.findOneBySuperiorIdAndSubordinateId(user.getId(), req.getUserId());
            if(userRelationship != null){
                // 再看看是否允许查看
                DiseaseReport diseaseReport = diseaseReportMapper.findOneByUserId(req.getUserId());
                if(diseaseReport != null && diseaseReport.getOtherView().equals(ToggleEnum.ON.getStatus())){
                }else{
                    req.setUserId(-1L);
                }
            }else{
                req.setUserId(-1L);
            }
        }else{
            req.setUserId(user.getId());
        }


        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<DiseaseReportHistory> list = diseaseReportHistoryMapper.findAllPage(req);
        return PageHelpUtil.buildPage(list, page);
    }
}